using DevExpress.XtraEditors;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using B.MESUI.Login.BasicData_UI;
using DevExpress.XtraGrid.Views.Grid;

namespace B.MESUI.Login.BasicData_UI.Customer
{
    public partial class GetSalesForm : XtraForm
    {
        private GetUserControl userControl;
        private string customerId;
        private int pageIndex = 1, pageSize = 10, totalCount = 0;
        private SimpleButton btnAdd;

        public class SalesRecordDTO
        {
            public string id { get; set; }
            public string sale_Code { get; set; }
            public string sale_Title { get; set; }
            public string department_Name { get; set; }
            public string sale_DateTime { get; set; }
            public string sale_Person { get; set; }
            public string sale_Money { get; set; }
            public string customer_ID { get; set; }
        }

        public GetSalesForm(string customerId)
        {
            InitializeComponent();
            this.customerId = customerId;
            InitUI();
            _ = LoadData();
        }

        private void InitUI()
        {
            this.Width = 1200;
            this.Height = 700;
            this.StartPosition = FormStartPosition.CenterScreen;
            userControl = new GetUserControl { Dock = DockStyle.Fill };
            this.Controls.Add(userControl);
            // 新增按钮
            btnAdd = new SimpleButton { Text = "新增", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
            btnAdd.Click += (s, e) =>
            {
                var addForm = new AddSalesForm(customerId);
                addForm.SalesAdded += async () => { await LoadData(); };
                addForm.ShowDialog();
            };
            // 新增按钮居中放置
            var panelBtn = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, Dock = DockStyle.Top, Height = 50, AutoSize = true, Padding = new Padding(0, 10, 0, 10) };
            panelBtn.Controls.Add(btnAdd);
            this.Controls.Add(panelBtn);
            panelBtn.BringToFront();
            // 查询字段
            var fields = new List<GetUserControl.QueryField>
            {
                new GetUserControl.QueryField { FieldName = "sale_Code", DisplayName = "销售单号", FieldType = GetUserControl.QueryFieldType.TextBox },
                new GetUserControl.QueryField { FieldName = "sale_Title", DisplayName = "销售标题", FieldType = GetUserControl.QueryFieldType.TextBox }
            };
            userControl.SetQueryFields(fields);
            userControl.btnQuery.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnReset.Click += async (s, e) =>
            {
                var qv = userControl.GetQueryValues();
                foreach (var k in qv.Keys)
                {
                    if (userControl.QueryControls[k] is DevExpress.XtraEditors.BaseEdit be)
                        be.EditValue = null;
                }
                pageIndex = 1;
                await LoadData();
            };
            userControl.btnPrev.Click += async (s, e) => { if (pageIndex > 1) { pageIndex--; await LoadData(); } };
            userControl.btnNext.Click += async (s, e) => { if (pageIndex < GetTotalPages()) { pageIndex++; await LoadData(); } };
            userControl.btnFirst.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnLast.Click += async (s, e) => { pageIndex = GetTotalPages(); await LoadData(); };
            userControl.btnJump.Click += async (s, e) =>
            {
                int jumpPage;
                if (int.TryParse(userControl.txtJump.Text, out jumpPage))
                {
                    if (jumpPage >= 1 && jumpPage <= GetTotalPages())
                    {
                        pageIndex = jumpPage;
                        await LoadData();
                    }
                }
            };
        }

        private int GetTotalPages() => (int)Math.Ceiling((double)totalCount / pageSize);

        private async Task LoadData()
        {
            string url = $"http://localhost:5198/api/Record/GetSales?ID={customerId}&PageIndex={pageIndex}&PageSize={pageSize}";
            var queryValues = userControl.GetQueryValues();
            if (queryValues.ContainsKey("sale_Code") && !string.IsNullOrWhiteSpace(queryValues["sale_Code"]?.ToString()))
                url += $"&sale_Code={queryValues["sale_Code"]}";
            if (queryValues.ContainsKey("sale_Title") && !string.IsNullOrWhiteSpace(queryValues["sale_Title"]?.ToString()))
                url += $"&sale_Title={queryValues["sale_Title"]}";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var resp = await client.GetAsync(url);
                    string json = await resp.Content.ReadAsStringAsync();
                    var jobj = JObject.Parse(json);
                    totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                    var pageList = jobj["pageDatas"] as JArray;
                    var dataList = new List<SalesRecordDTO>();
                    if (pageList != null)
                    {
                        foreach (var item in pageList)
                        {
                            dataList.Add(item.ToObject<SalesRecordDTO>());
                        }
                    }
                    var gridControl = userControl.MainGrid;
                    if (gridControl != null)
                    {
                        gridControl.DataSource = dataList;
                        var gridView = gridControl.MainView as GridView;
                        if (gridView != null)
                        {
                            if (gridView.Columns["sale_Code"] != null)
                                gridView.Columns["sale_Code"].Caption = "销售单号";
                            if (gridView.Columns["sale_Title"] != null)
                                gridView.Columns["sale_Title"].Caption = "销售标题";
                            if (gridView.Columns["department_Name"] != null)
                                gridView.Columns["department_Name"].Caption = "部门名称";
                            if (gridView.Columns["sale_DateTime"] != null)
                                gridView.Columns["sale_DateTime"].Caption = "销售日期";
                            if (gridView.Columns["sale_Person"] != null)
                                gridView.Columns["sale_Person"].Caption = "销售人员";
                            if (gridView.Columns["sale_Money"] != null)
                                gridView.Columns["sale_Money"].Caption = "销售金额";
                            // 表头加粗居中，内容居中
                            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
                            {
                                col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                                col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold);
                                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                            }
                            // 行号
                            gridView.IndicatorWidth = 40;
                            gridView.CustomDrawRowIndicator += (s, e) =>
                            {
                                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                                {
                                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                                }
                            };
                            // 滚动条
                            gridView.OptionsView.ColumnAutoWidth = false;
                            gridView.BestFitColumns();
                            gridView.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.True;
                            gridView.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.True;
                            gridView.OptionsView.RowAutoHeight = true;
                        }
                    }
                    userControl.lblPageInfo.Text = $"第{pageIndex}/{(GetTotalPages() == 0 ? 1 : GetTotalPages())}页 共{totalCount}条";
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }

    // 新增销售记录表单
    public class AddSalesForm : XtraForm
    {
        public event Action SalesAdded;
        private string customerId;
        private TextEdit txtSaleCode, txtSaleTitle, txtDepartment, txtDateTime, txtPerson, txtMoney, txtCustomerId;
        private SimpleButton btnSave, btnCancel;
        public AddSalesForm(string customerId)
        {
            this.Text = "新增销售记录";
            this.Width = 500;
            this.Height = 480;
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            // TableLayoutPanel整体居中
            var table = new TableLayoutPanel
            {
                RowCount = 8,
                ColumnCount = 2,
                Dock = DockStyle.Fill,
                Padding = new Padding(30, 30, 30, 30),
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
            };
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35F));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 65F));
            for (int i = 0; i < 8; i++)
                table.RowStyles.Add(new RowStyle(SizeType.Absolute, 40F));
            var lblSaleCode = new Label() { Text = "销售单号：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtSaleCode = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblSaleTitle = new Label() { Text = "销售标题：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtSaleTitle = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblDepartment = new Label() { Text = "部门名称：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtDepartment = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblDateTime = new Label() { Text = "销售日期：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtDateTime = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblPerson = new Label() { Text = "销售人员：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtPerson = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblMoney = new Label() { Text = "销售金额：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtMoney = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220 };
            var lblCustomerId = new Label() { Text = "客户ID：", Anchor = AnchorStyles.Right, AutoSize = true, TextAlign = ContentAlignment.MiddleRight };
            txtCustomerId = new TextEdit() { Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 220, ReadOnly = true, Enabled = false, Text = customerId };
            // 按钮行
            var panelBtn = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, Dock = DockStyle.Fill, Anchor = AnchorStyles.None, AutoSize = true };
            btnSave = new SimpleButton() { Text = "保存", Width = 90, Height = 32 };
            btnCancel = new SimpleButton() { Text = "取消", Width = 90, Height = 32 };
            btnSave.Click += async (s, e) => await SaveSales();
            btnCancel.Click += (s, e) => this.Close();
            panelBtn.Controls.Add(btnSave);
            panelBtn.Controls.Add(btnCancel);
            // 添加到表格
            table.Controls.Add(lblSaleCode, 0, 0); table.Controls.Add(txtSaleCode, 1, 0);
            table.Controls.Add(lblSaleTitle, 0, 1); table.Controls.Add(txtSaleTitle, 1, 1);
            table.Controls.Add(lblDepartment, 0, 2); table.Controls.Add(txtDepartment, 1, 2);
            table.Controls.Add(lblDateTime, 0, 3); table.Controls.Add(txtDateTime, 1, 3);
            table.Controls.Add(lblPerson, 0, 4); table.Controls.Add(txtPerson, 1, 4);
            table.Controls.Add(lblMoney, 0, 5); table.Controls.Add(txtMoney, 1, 5);
            table.Controls.Add(lblCustomerId, 0, 6); table.Controls.Add(txtCustomerId, 1, 6);
            table.SetColumnSpan(panelBtn, 2);
            table.Controls.Add(panelBtn, 0, 7);
            this.Controls.Clear();
            this.Controls.Add(table);
        }
        private async Task SaveSales()
        {
            var data = new
            {
                id = "string",
                sale_Code = txtSaleCode.Text.Trim(),
                sale_Title = txtSaleTitle.Text.Trim(),
                department_Name = txtDepartment.Text.Trim(),
                sale_DateTime = txtDateTime.Text.Trim(),
                sale_Person = txtPerson.Text.Trim(),
                sale_Money = txtMoney.Text.Trim(),
                customer_ID = customerId
            };
            using (HttpClient client = new HttpClient())
            {
                var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                var resp = await client.PostAsync("http://localhost:5198/api/Record/AddSales", content);
                string json = await resp.Content.ReadAsStringAsync();
                if (resp.IsSuccessStatusCode && json.Contains("成功"))
                {
                    XtraMessageBox.Show("添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SalesAdded?.Invoke();
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("添加失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
} 